<template>
  <div class="common-wrapper l-f l-col-stretch" id="common-wrapper">
    <div class="left">
      <a-card style="height: 100%;display: flex;flex-direction: column;" :bodyStyle="{
        overflowY: 'auto'
      }">
        <div slot="title" class="l-f l-row-sb" v-if="role_key == 1">
          <a-button @click="departmentAdd" type="primary" icon="plus" size="small" :disabled="selectedKeys.length === 0 || selectedKeys.length === 1 ? false : true">添加</a-button>
          <a-button @click="departmentEdit" type="primary" icon="edit" size="small" :disabled="selectedKeys.length === 1 ? false : true">修改</a-button>
          <a-button @click="departmentDel" type="danger" icon="delete" size="small" :disabled="selectedKeys.length > 0 ? false : true">删除</a-button>
        </div>
        <a-tree
          :show-line="true"
          :tree-data="departmentList"
          :replaceFields="replaceFields"
          :defaultExpandAll="true"
          :selected-keys="selectedKeys"
          multiple
          :key="treeKey"
          @select="onTreeSelect"
        />
      </a-card>
    </div>
    <div class="right">
      <div class="common-search">
        <a-form-model :model="queryForm" layout="inline">
          <div class="l-f l-row-sb">
            <div>
              <a-form-model-item label="姓名">
                <a-input v-model="queryForm.name" placeholder="请输入" style="width: 90px" />
              </a-form-model-item>  
              <a-form-model-item label="工号">
                <a-input v-model="queryForm.id_card" placeholder="请输入" style="width: 100px" />
              </a-form-model-item>
              <a-form-model-item label="工种">
                <a-select v-model="queryForm.work_type" mode="multiple" style="width: 185px">
                  <a-select-option v-for="item in workList" :key="item.data_value">
                    {{ item.data_name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
               <a-form-model-item label="同步状态">
              <a-select v-model="queryForm.sync_state" style="width: 95px">
                <a-select-option v-for="item in statusList" :key="item.value" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
              <!-- <a-form-model-item label="部门">
              <a-select mode="multiple" v-model="queryForm.department_names" style="width: 200px">
                <a-select-option value="">全部部门</a-select-option>
                <a-select-option v-for="item in departments" :key="item.pkey" :value="item.dep_name">
                  {{ item.dep_name }}
                </a-select-option>
              </a-select>
            </a-form-model-item> -->
            </div>
            <a-form-model-item>
              <a-button @click="getTableData" type="primary" icon="search" class="l-mg-r10">搜索</a-button>
              <a-button @click="onImport" type="primary" icon="upload" class="l-mg-r10">导入</a-button>
              <a-button @click="onAdd" type="primary" icon="plus" class="l-mg-r10">添加</a-button>
              <a-button @click="onBatchDepartmentEdit" type="primary" icon="edit" :disabled="!hasSelected" class="l-mg-r10">部门修改</a-button>
              <a-button @click="onBatchWorkEdit" type="primary" icon="edit" :disabled="!hasSelected" class="l-mg-r10">工种修改</a-button>
              <!-- <a-button @click="onEdit" type="primary" icon="edit" class="l-mg-r10" :disabled="selectedRowKeys.length === 1 ? false : true">修改</a-button> -->
              <a-button @click="onDel" type="danger" icon="delete" :disabled="!hasSelected">删除</a-button>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
      <div class="common-main" ref="main">
        <a-table
          size="middle"
          rowKey="pkey"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :scroll="{ y: isShowForm ? 300 : 550,x: 1200 }"
          :data-source="dataSource"
          bordered
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
        >
        <template slot="index" slot-scope="text, record, index">
          {{ index + 1 }}
        </template>
        <template slot="is_black_list" slot-scope="text, record">
          <!-- 是否是黑名单 1不是 2是 0离职 -->
          {{ record.is_black_list == 1 ? '不是' : record.is_black_list == 2 ? '是' : '离职' }}
        </template>
        <template slot="sync_state" slot-scope="text, record">
          <!-- 同步状态 0待同步 1同步成功 2同步失败 -->
          <a-tooltip placement="top">
            <template slot="title">
              <span>同步结果: {{record.sync_result}}</span>
            </template>
            {{ record.sync_state == 1 ? '同步成功' : record.sync_state == 2 ? '同步失败' : '待同步' }}
          </a-tooltip>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button @click="onEdit(record.pkey)" type="link" icon="edit" size="small">修改</a-button>
        </template>
        </a-table>
        <template v-if="isShowForm">
          <a-divider orientation="left">人员详细信息</a-divider>
          <PeopleForm ref="peopleFormRef" @saveSuccess="isShowForm = false" />
        </template>
      </div>
    </div>
    <DepartmentForm ref="departmentFormRef" />
    <ImportForm ref="importFormRef" />
    <DepartmentOrWorkForm ref="departmentOrWorkForm" @saveSuccess="batchSaveSuccess" />
  </div>
</template>
  
  <script>
import { getDepartmentList,getDatadictionary } from '@/api/plan'
import DepartmentForm from './components/department/DepartmentForm.vue'
import PeopleForm from './components/people/PeopleForm.vue'
import ImportForm from './components/people/ImportForm.vue'
import DepartmentOrWorkForm from './components/people/DepartmentOrWorkForm.vue'

import { getDepartmentThreeListApi, delDepartment,getPeopleListApi,delPeopleApi } from '@/api/people'
import { mapState } from 'vuex'

export default {
  components: {
    DepartmentForm,
    PeopleForm,
    ImportForm,
    DepartmentOrWorkForm
  },
  computed: {
    ...mapState(['role_key']),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
  },
  data() {
    const columns = [
      {
        title: '编号',
        dataIndex: 'pkey',
        align: 'center',
        width: 60,
        // scopedSlots: { customRender: 'index' },
      },
      {
        title: '工号',
        dataIndex: 'person_idcard',
        align: 'center',
        width: 120,
      },
      {
        title: '名称',
        dataIndex: 'person_name',
        align: 'center',
        width: 120,
      },
      {
        title: '性别',
        dataIndex: 'person_sex',
        align: 'center',
        width: 80,
      },
      {
        title: '工种',
        dataIndex: 'work_type_name',
        align: 'center',
        width: 120,
      },
      {
        title: '部门',
        dataIndex: 'dep_name',
        align: 'center',
        width: 120,
      },
      {
        title: '入职时间',
        dataIndex: 'person_come_date',
        align: 'center',
        width: 150,
      },
      {
        title: '是否是黑名单',
        dataIndex: 'is_black_list',
        align: 'center',
        width: 120,
        scopedSlots: { customRender: 'is_black_list' },
      },
      {
        title: '同步状态',
        dataIndex: 'sync_state',
        align: 'center',
        width: 80,
        scopedSlots: { customRender: 'sync_state' },
      },
      {
        title: '离职时间',
        dataIndex: 'person_out_date',
        align: 'center',
        width: 150,
      },
      {
        title: '电话',
        dataIndex: 'person_phone',
        align: 'center',
        width: 120,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        align: 'center',
        width: 180,
      },
      {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        width: 100,
        fixed: 'right',
        scopedSlots: { customRender: 'action' },
      }
    ]
    return {
      replaceFields: {
        children: 'childs',
        title: 'dep_name',
        key: 'pkey',
      },
      // 部门列表
      departmentList: [
        {
          key: 0,
          dep_name: '全部',
          childs: [],
          disabled: true,
        }
      ],
      selectedKeys: [], // 部门勾选
      parentName: '全部',
      // 当前部门选择
      selectDepartment: [],
      queryForm: {
        name: '',
        id_card: '',
        work_type: [],
        sync_state: -1,
        department_names: ''
      },
      // 工种列表
      workList: [],
      statusList: [
        {
          name: "全部",
          value: -1
        },
        {
          name: "待同步",
          value: 0
        },
        {
          name: "同步成功",
          value: 1
        },
        {
          name: "同步失败",
          value: 2
        }
      ],
      typeList: [
        {
          name: '全部类型',
          value: '',
        },
      ],
      // 部门列表
      departments: [],
      columns,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        pageSizeOptions: ['10', '20', '30', '40', '50','100','500','1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      loading: false,
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      treeKey: 0,
      isShowForm: false,
    }
  },
  created() {
    this.getDepartmentThreeList()
    this.getWorkList()
    this.getDepartmentList()
    this.getTableData()
  },
  methods: {
    // 部门添加
    departmentAdd() {
      let selectDepartment = {
        parent_key: 0,
        pKey: '',
        dep_name: '',
        parent_name: '全部'
      }
      this.$refs.departmentFormRef.add(this.selectDepartment.length === 1 ? this.selectDepartment[0] : selectDepartment)
    },
    // 部门编辑
    departmentEdit() {
      this.$refs.departmentFormRef.edit(this.selectDepartment[0])
    },
    // 部门删除
    departmentDel() {
      this.$confirm({
          title: '提示',
          content: '确定删除吗？',
          onOk: async () => {
            const {statusCode,data,errors} = await delDepartment({
              pkeys: this.selectedKeys
            })
            if(statusCode == 200) {
              this.$message.success('删除成功！')
              this.getDepartmentThreeList()
            }else {
              this.$message.error(errors)
            }
          }
        });
    },
    onTreeSelect(selectedKeys, e) {
      this.selectedKeys = selectedKeys
      if (e.selected) {
        let selectDepartment = {
          pKey: e.node.eventKey,
          dep_name: e.node.title,
          parent_name: e.node.title,
          parent_key: e.node.dataRef.pkey ? e.node.dataRef.pkey : 0
        }
        this.selectDepartment.push(selectDepartment)
      } else {
        for (let i = 0; i < this.selectDepartment.length; i++) {
          if(this.selectDepartment[i].pKey === e.node.eventKey){
            this.selectDepartment.splice(i,1)
            break
          }
        }
      }
      this.getTableData()
    },
    // 导入
    onImport() {
      this.$refs.importFormRef.add()
    },
    // 添加
    onAdd() {
      this.isShowForm = true
      this.$nextTick(() => {
        this.$refs.peopleFormRef.add()
        document.querySelector('#common-wrapper').scrollTop = 9999
      })
    },
    // 修改
    onEdit(pkey) {
      this.isShowForm = true
      this.$nextTick(() => {
        this.$refs.peopleFormRef.edit(pkey)
        document.querySelector('#common-wrapper').scrollTop = 9999
      })
    },
    batchSaveSuccess() {
      this.selectedRows = []
      this.selectedRowKeys = []
    },
    // 批量部门修改
    onBatchDepartmentEdit() {
      this.$refs.departmentOrWorkForm.edit(1,this.selectedRowKeys)
    },
    // 批量工种修改
    onBatchWorkEdit() {
      this.$refs.departmentOrWorkForm.edit(2,this.selectedRowKeys)
    },
    // 删除
    onDel() {
      this.$confirm({
        title: '提示',
        content: '确定删除吗？',
        onOk: async () => {
          const { statusCode, errors } = await delPeopleApi({
            pkeys: this.selectedRowKeys,
          })
          if (statusCode == 200) {
            this.$message.success('删除成功！')
            this.selectedRowKeys = []
            this.getTableData()
          } else {
            this.$message.error(errors)
          }
        },
      })
    },
    // 选择数据
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.getTableData()
    },
    // 获取部门列表
    async getDepartmentThreeList() {
      const { data } = await getDepartmentThreeListApi()
      this.departmentList[0].childs = data
      this.selectedKeys = []
      this.selectDepartment = []
      this.treeKey += 1
    },
    // 获取人员列表
    async getTableData() {
      this.loading = true
      let department_names = this.selectedKeys.join(',')
      let work_types = this.queryForm.work_type.join(',')
      const { data } = await getPeopleListApi({
        ...this.queryForm,
        department_names,
        work_types,
        page_index: this.pagination.current,
        page_size: this.pagination.pageSize,
      })
      this.loading = false
      let list = data.items
      for (let i = 0; i < list.length; i++) {
        list[i].person_come_date = list[i].person_come_date ? list[i].person_come_date.substring(0,10) : ''
        list[i].person_out_date = list[i].person_out_date ? list[i].person_out_date.substring(0,10) : ''
      }
      this.dataSource = list
      this.pagination.total = data.totalCount
    },
    // 获取部门列表
    async getDepartmentList() {
      const { data } = await getDepartmentList()
      this.departments = data
    },
    // 获取工种列表
    async getWorkList() {
      const { data } = await getDatadictionary({ data_type: 3 })
      this.workList = this.workList.concat(data)
    },
  },
}
</script>
  
  <style lang="less" scoped>
.left {
  width: 270px;
}
.right {
  flex: 1;
  min-width: 0;
  padding-left: 20px;
  box-sizing: border-box;
}
.cancel-btn {
  background-color: #ff9f43;
  border-color: #ff9f43;
}
</style>